import { getDiscountInfo, getGoodPriceInfo, getHighScoreInfo, getHotRecommend, getLongfor, getPlus } from '@/services'
import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'

const slice = createSlice({
    name: 'home',
    initialState: {
        goodPriceInfo: null,  // 高性价比房源列表
        highScoreInfo: null,  // 高评分房源列表
        discountInfo: null,   // 打折房源列表
        hotRecommendInfo: null, // 热门推荐房源列表
        plusInfo: null,        // plus房源列表
        longforInfo: null      // 你可能想去房源列表
    },
    reducers:{
        changeGoodPriceInfoAction(state, {payload}) {
            state.goodPriceInfo = payload
        },
        changeHighScoreAction(state, {payload}){
            state.highScoreInfo = payload
        },
        changeDiscountInfoAction(state, {payload}){
            state.discountInfo = payload
        },
        changeHotRecommendInfoAction(state, {payload}){
            state.hotRecommendInfo = payload
        },
        changePlusInfoAction(state, {payload}){
            state.plusInfo = payload
        },
        changeLongforInfoAction(state, {payload}){
            state.longforInfo = payload
        }
    }
})
// 统一请求首页所有需要的数据
export const fetchHomeDataAction = createAsyncThunk('fetchHomeData', async (arg, {dispatch}) => {
    
    try {
        const goodPriceInfo = await getGoodPriceInfo()
        // if(goodPriceInfo.code !== "ERR_NETWORK")
        dispatch(changeGoodPriceInfoAction(goodPriceInfo))

        const highScoreInfo = await getHighScoreInfo()
        // if(highScoreInfo.code !== "ERR_NETWORK")
        dispatch(changeHighScoreAction(highScoreInfo))

        const discountInfo = await getDiscountInfo()
        // if(discountInfo.code !== "ERR_NETWORK")
        dispatch(changeDiscountInfoAction(discountInfo))

        const hotRecommendInfo = await getHotRecommend()
        // if(hotRecommendInfo.code !== "ERR_NETWORK")
        dispatch(changeHotRecommendInfoAction(hotRecommendInfo))
        
        const plusInfo = await getPlus()
        // if(plusInfo.code !== "ERR_NETWORK")
        dispatch(changePlusInfoAction(plusInfo))

        const longforInfo = await getLongfor()
        // if(longforInfo.code !== "ERR_NETWORK")
        dispatch(changeLongforInfoAction(longforInfo))
    } catch (error) {
        console.log("数据请求失败，请检查您的网络", error)
    }
})

export const {
    changeGoodPriceInfoAction, 
    changeHighScoreAction, 
    changeDiscountInfoAction, 
    changeHotRecommendInfoAction,
    changePlusInfoAction,
    changeLongforInfoAction
} = slice.actions
export default slice.reducer